<template>
  <div class="purchase-detail">
    <el-dialog
      :title="detailData.title"
      v-model="detailData.dialogFormVisible"
      destroy-on-close
      width="520px"
    >
      <el-form
        class="content"
        :model="formData"
        :rules="formRules"
        ref="formDataRef"
        label-width="120px"
      >
        <el-form-item label="项目名称" prop="projectInfo">
          <el-select
            clearable
            filterable
            placeholder="请选择项目"
            style="width: 100%"
            v-model="formData.projectInfo"
            @change="selectProject"
          >
            <el-option
              v-for="item in projectList"
              :label="item.projectName"
              :key="item.id"
              :value="`${item.id},${item.projectName},${item.projectTypeCode},${item.projectTypeName},${item.projectLeaderId},${item.projectLeaderName}`"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="项目类型">
          <span class="text--info">{{ formData.projectTypeName }}</span>
        </el-form-item>

        <el-form-item label="项目管理员">
          <span class="text--info">{{ formData.leaderName }}</span>
        </el-form-item>
        <!-- 除了B类设备之外，都能选择标段 -->
        <el-form-item
          label="项目标段"
          prop="sectionInfo"
          v-if="formData.projectTypeCode !== 'B'"
        >
          <el-select
            clearable
            filterable
            placeholder="请选择项目标段"
            style="width: 100%"
            v-model="formData.sectionInfo"
            @change="selectSection"
          >
            <el-option
              v-for="item in sectionList"
              :label="item.sectionName"
              :key="item.id"
              :value="`${item.id},${item.sectionName}`"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="预算金额" prop="budgetAmount">
          <el-input
            class="text--info"
            v-model="formData.budgetAmount"
            placeholder="请输入预算金额"
          >
            <template #append>万元</template>
          </el-input>
        </el-form-item>

        <el-form-item label="合同金额" prop="contractAmount">
          <el-input
            class="text--info"
            v-model="formData.contractAmount"
            placeholder="请输入合同金额"
          >
            <template #append>万元</template>
          </el-input>
        </el-form-item>

        <el-form-item label="费率" prop="rate">
          <el-input
            class="text--info"
            v-model="formData.rate"
            placeholder="请输入费率"
          >
            <template #append>%</template>
          </el-input>
        </el-form-item>
      </el-form>
      <el-row justify="end" class="form__footer">
        <el-button @click="handleSubmit(false)">取消</el-button>
        <el-button type="primary" @click="handleSubmit(true)">确定</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, toRefs } from "vue";
import {
  addProjectBudget,
  updateProjectBudget,
  projectBudgetInfo
} from "/@/api/purchase";
import { projectManageList, getSection } from "/@/api/projects";
import NotifMessage from "/@/utils/message/notification";
import { ElMessageBox } from "element-plus";
export default defineComponent({
  name: "purchaseDetail",
  props: {
    detailData: {
      type: Object,
      default: () => {}
    },
    jcProjectInfo: {
      type: Object,
      default: () => {}
    },

    totalAmount: {
      type: Number,
      default: 0
    },

    remainAmount: {
      type: Number,
      default: 0
    }
  },
  emits: ["emitClose", "updateClose"],
  setup(props, { emit }) {
    const formDataRef = ref<HTMLFormElement | null>(null) as any;
    const projectList = ref([]);
    const sectionList = ref([]);
    const currentAmount = ref<number>(0); //当前关联项目的预算
    let state = reactive({
      formData: {
        addMethod: "1",
        projectInfo: "" as any,
        projectId: "",
        projectName: "",
        projectTypeCode: "",
        projectTypeName: "",
        leaderId: "",
        leaderName: "",
        sectionInfo: "" as any,
        sectionId: "",
        sectionName: "",
        rate: "",
        contractAmount: "",
        budgetAmount: "",
        jcProjectId: props.jcProjectInfo?.jcProjectId,
        jcProjectName: props.jcProjectInfo?.jcProjectName,
        budgetName: "",
        budgetTypeCode: "",
        budgetTypeName: ""
      }
    });
    const validateAmount = (rule: any, value: any, callback: any) => {
      if (!value) {
        callback();
      } else {
        const reg = /^(([1-9]\d*)|0)(\.\d{1,5})?$/;
        if (!reg.test(value)) {
          if (rule.field === "rate") {
            return callback(new Error("请输入正确的费率"));
          } else {
            return callback(new Error("请输入正确的金额格式"));
          }
        } else {
          callback();
        }
      }
    };

    const formRules = ref({
      projectInfo: [
        { required: true, message: "请选择项目名称", trigger: "change" }
      ],
      sectionInfo: [
        { required: true, message: "请选择项目标段", trigger: "change" }
      ],
      budgetAmount: [{ validator: validateAmount, trigger: "blur" }],
      contractAmount: [{ validator: validateAmount, trigger: "blur" }],
      rate: [{ validator: validateAmount, trigger: "blur" }]
    });

    // 确认提交
    const handleSubmit = async (isSubmit: boolean) => {
      if (isSubmit) {
        const isValid = await new Promise(resolve =>
          formDataRef.value.validate(resolve)
        );
        if (!isValid) return;
        if (String(props.detailData.id)) {
          updateBudget();
        } else {
          addBudget();
        }
      } else {
        emit("emitClose");
      }
    };

    //新增集采关联项目
    const addBudget = async () => {
      if (Number(state.formData.budgetAmount) > Number(props.remainAmount)) {
        //当前新增关联项目的预算金额大于剩余总的预算金额
        ElMessageBox.confirm("项目预算超支，确定新增该预算金额", "", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          iconClass: "el-icon-warning"
        })
          .then(() => {
            submitAddBudget();
          })
          .catch(() => {});
      } else {
        submitAddBudget();
      }
    };

    const submitAddBudget = async () => {
      try {
        const { code, message } = await addProjectBudget(state.formData);
        if (code === 200) {
          NotifMessage.success(message);
          emit("updateClose");
        }
      } catch (err) {
        console.log("error", err);
      }
    };

    //更新集采关联项目
    const updateBudget = async () => {
      if (
        Number(state.formData.budgetAmount) - Number(currentAmount.value) >
        Number(props.remainAmount)
      ) {
        //新的所有关联项目的总预算
        ElMessageBox.confirm("项目预算超支，确定修改该预算金额", "", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          iconClass: "el-icon-warning"
        })
          .then(() => {
            submitUpdateBudget();
          })
          .catch(() => {});
      } else {
        submitUpdateBudget();
      }
    };

    //更新集采关联项目
    const submitUpdateBudget = async () => {
      try {
        const { code, message } = await updateProjectBudget(state.formData);
        if (code === 200) {
          NotifMessage.success(message);
          emit("updateClose");
        }
      } catch (err) {
        console.log("error", err);
      }
    };

    // 获取详情
    const getBudgetInfo = async purId => {
      try {
        let postData = { id: purId };
        const { code, data } = await projectBudgetInfo(postData);
        if (code === 200) {
          state.formData = data;
          console.log(state.formData, "formDataformDataformData");
          state.formData.projectInfo = data.projectName;
          state.formData.sectionInfo = data.sectionName;
          currentAmount.value = data.budgetAmount;
          // formData.projectInfo = `${data.projectId},${data.projectName},${data.projectTypeCode},${data.projectTypeName},${data.leaderId},${data.leaderName},`
          // formData.sectionInfo = `${data.sectionId},${data.sectionName}`
          // formData.professionDirInfo = {
          //   dicValue:formData.professionDirName,
          //   dicCode:formData.professionDirCode
          // }
          // formData.purchasSchemeInfo = {
          //   dicValue:formData.purchasSchemeName,
          //   dicCode:formData.purchasSchemeCode
          // }
        }
      } catch (err) {
        console.log(err);
      }
    };

    //获取项目列表
    const getTableData = async () => {
      const formSearch = {
        projectNameLike: "",
        projectRegionCode: "",
        projectFactoryNameLike: "",
        projectLeaderNameLike: "",
        projectTypeCode: "",
        projectYear: "",
        createTimeStrStart: "",
        createTimeStrEnd: "",
        pageNum: 1,
        pageSize: 200
      };
      const { code, data } = await projectManageList({ ...formSearch });
      if (code === 200) {
        projectList.value = data.list;
      }
    };

    // 选择项目
    const selectProject = async item => {
      const proArray = item.split(",");
      state.formData.projectId = proArray[0];
      state.formData.projectName = proArray[1];
      state.formData.projectTypeCode = proArray[2];
      state.formData.projectTypeName = proArray[3];
      state.formData.leaderId = proArray[4];
      state.formData.leaderName = proArray[5];
      state.formData.sectionInfo = "";
      state.formData.sectionId = "";
      state.formData.sectionName = "";
      if (state.formData.projectId && state.formData.projectTypeCode !== "B") {
        getSectionData(state.formData.projectId);
      }
    };

    //获取标段列表
    const getSectionData = async projectId => {
      let obj = {
        projectId: +projectId,
        pageNum: 1,
        pageSize: 500
      };
      try {
        const { code, data } = await getSection(obj);
        if (code === 200) {
          sectionList.value = data.list;
        }
      } catch (err) {
        console.log(err);
      }
    };

    // 选择项目
    const selectSection = async item => {
      const secArray = item.split(",");
      state.formData.sectionId = secArray[0];
      state.formData.sectionName = secArray[1];
    };

    getTableData();
    if (String(props.detailData.id)) {
      getBudgetInfo(props.detailData.id);
    }
    return {
      ...toRefs(state),
      handleSubmit,
      formRules,
      formDataRef,
      projectList,
      sectionList,
      selectProject,
      selectSection
    };
  }
});
</script>
<style lang="scss" scoped>
:deep.purchase-detail {
  .content {
    padding-right: 46px;
  }
}
</style>
